import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 15000, // 请求超时时间
  withCredentials: true,
  crossDomain: true
})

var _token = ''

// request拦截器
service.interceptors.request.use(config => {
	let regWord = /[\u4e00-\u9fa5]/
	if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      if(!regWord.test(getToken())){
      	config.headers['token'] = getToken()
      }
    }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    /*if( res.data ){
    	if(res.data.token)
    	_token = res.data.token
    }*/
    
    if (res.code == '401') {
      // Message.error(res.message)
      MessageBox.confirm('登录时间超时，请重新登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      })
    }
    return res
  },
  error => {
    console.log('err' + error)// for debug
    /*Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })*/
    if (error.response && error.response.status === 401) {
    	 MessageBox.confirm('登录时间超时，请重新登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      })
    }
    return Promise.reject(error)
  }
)

export default service
